package com.learn.netty.bio;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author zhongshitao
 * @date 2020/10/12 10:02 上午
 */
@Slf4j
public class BIOServerDemo {


    /**
     * 通过bio做一个server服务
     * 1.创建多线程
     * 2.监听本地端口
     * @param args
     */
    public static void main(String[] args) throws Exception {
        ExecutorService executorService = Executors.newCachedThreadPool();
        ServerSocket server = new ServerSocket(8888);
        log.info("服务器已启动...");
        log.info("监听端口:8888");
        while (true) {
            final Socket socket = server.accept();
            log.info("客户端连接...");
            executorService.execute(() -> {
                handler(socket);
            });
        }


    }

    private static void handler(Socket socket) {
        log.info("---当前线程id={},线程名称={}", Thread.currentThread().getId(), Thread.currentThread().getName());
        if (null == socket) {
            log.error("连接为空");
            return;
        }
        byte[] bytes = new byte[1024];
        try {
            InputStream inputStream = socket.getInputStream();
            int read = -1;
            while ((read = inputStream.read(bytes)) > -1) {
                log.info(new String(bytes, 0, read));
            }
        } catch (IOException e) {
            log.error(e.getMessage(),e);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                log.info("客户端连接关闭,线程id={}", Thread.currentThread().getId());
                socket.close();
            } catch (IOException e) {
                log.error(e.getMessage(),e);
            }
        }
    }
}
